package userrepository

import (
	"strconv"
	"time"
	ds "zzxq/common/datasource"
	"zzxq/common/logger"

	"github.com/go-redis/redis/v8"
)

type RedisLogin struct {
}

//设置登录验证码的redis-key
func (login *RedisLogin) keyLoginCode(phone string) string {
	return "user:login:code:" + phone
}

//设置登录验证码
func (login *RedisLogin) SetLoginCode(phone string, code string) {
	err := ds.GetRedis().SetEX(ds.Ctx, login.keyLoginCode(phone), code, time.Minute*15).Err()
	if err != nil {
		logger.GetLog().Error("redis err:", err)
	}
}

//获取登录验证码
func (login *RedisLogin) GetLoginCode(phone string) string {
	code, err := ds.GetRedis().Get(ds.Ctx, login.keyLoginCode(phone)).Result()
	if err != nil && redis.Nil != err {
		logger.GetLog().Error("redis err:", err)
	}

	return code
}

type RedisUser struct{}

//用户信息redis-key
func (user *RedisUser) keyUser(uid int) string {
	return "user:info:" + strconv.Itoa(uid)
}

//设置用户信息
func (user *RedisUser) SetUsrinfo(uid int, info map[string]interface{}) {
	err := ds.GetRedis().HSet(ds.Ctx, user.keyUser(uid), info).Err()
	if err != nil {
		logger.GetLog().Error("redis err user-info", err)
	}
}

//获取用户参数
func (user *RedisUser) GetUserInfo(uid int, fields ...string) interface{} {
	info, err := ds.GetRedis().HMGet(ds.Ctx, user.keyUser(uid), fields...).Result()
	if err != nil && redis.Nil != err {
		logger.GetLog().Error("rediserr get-user-info", err)
	}

	return info
}

//获取用户全部信息
func (user *RedisUser) GetAllUserInfo(uid int) map[string]string {
	info, err := ds.GetRedis().HGetAll(ds.Ctx, user.keyUser(uid)).Result()
	if err != nil {
		logger.GetLog().Error("rediserr get-all-user-info", err)
	}

	return info
}
